<template>
  <div class="namePop">
    <!-- 顶端导航栏 -->
    <van-nav-bar
      title="昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('quit')"
      @click-right="onClickRight"
    />

    <!-- 文本框 -->
    <van-field
      v-model.trim="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="7"
      placeholder="请输入昵称"
      show-word-limit
    />
  </div>
</template>

<script>
// 编辑用户个人资料api
import { edituser } from '@/assets/api/user'
export default {
  name: 'namePop',
  props: {
    value: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      message: this.value
    }
  },
  methods: {
    async onClickRight() {
      // 判断输入框的值是否有值
      if (this.message === '') {
        return this.$toast('请填写昵称')
      }

      // 进行慢加载处理

      this.$toast.loading({
        message: '保存中',
        forbidClick: true,
        // 持续展示
        duration: 0
      })

      try {
        // 发起ajax请求
        var { data: res } = await edituser({
          name: this.message
        })
      } catch {
        // 处理请求错误
        return this.$toast('更改昵称失败，请取消后重试')
      }
      // 告知父组件修改昵称完成
      this.$toast('更新成功')
      this.$emit('finish', res.data.name)
    }
  }
}
</script>

<style lang="less" scoped>
.namePop {
  background-color: #f5f7f9;
  /deep/ .van-nav-bar {
    background-color: #fff;
    .van-nav-bar__title {
      color: #000 !important;
    }
  }
  .van-field {
    width: auto;
    margin: 15px 30px;
  }
}
</style>
